﻿
using Abp.Domain.Repositories;
using Abp.Linq.Extensions;
using System;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;

namespace LpbPrj.Client.Options
{
    public class OptionService : ClientAppServiceBase, IOptionService
    {
        private readonly IRepository<Option> _optionRepository;

        public OptionService(IRepository<Option> optionRepository)
        {
            _optionRepository = optionRepository;
        }

        public async Task<T> GetOptionValue<T>(string item, long? creatorUserId)
        {
            string str = await _optionRepository.GetAll().AsNoTracking()
                .WhereIf(creatorUserId.HasValue, p => p.CreatorUserId.HasValue && p.CreatorUserId.Value == creatorUserId)
                .Where(p => p.Item.Equals(item)).Select(p => p.Item).FirstOrDefaultAsync();

            if (string.IsNullOrEmpty(str))
                return default(T);
            return (T)Convert.ChangeType(str, typeof(T));
        }

        public async Task AddOrUpdateOption(string item, string value, long? creatorUserId)
        {
            var entity = await _optionRepository.GetAll().AsNoTracking()
                .WhereIf(creatorUserId.HasValue, p => p.CreatorUserId.HasValue && p.CreatorUserId.Value == creatorUserId)
                .Where(p => p.Item.Equals(item)).FirstOrDefaultAsync();

            if (entity == null)
            {
                entity = new Option()
                {
                    Item = item,
                    Value = value,
                    CreatorUserId = creatorUserId,
                    CreationTime = DateTime.Now
                };
                await _optionRepository.InsertAsync(entity);
                return;
            }

            entity.Value = value; 
            await _optionRepository.UpdateAsync(entity);
        }
    }
}
